#import cparse_old
from js_parser import *
#import js_parser
import ply.yacc as yacc
import sys
from ply.lex import LexError
from final_code_gen import FCG
from final_code_exception import FinalCodeException


class Compiler:
	def _parse(self):
		"""llama al parser !!"""	
		self.slr=yacc.parse(self.code,debug=0)

	def compile(self,code):
		self.code = code
		try:
			self._parse()
        	#except js_parser.ParseError:
        	except ParseError:
        		return 1            

		return yacc.semanticError

def run_compiler():
	if len(sys.argv) < 2:
		print "Uso: cc.py file.js"
		sys.exit(1)

	file = sys.argv[1]

	source_filename = file
	source = open(source_filename, 'r')
	code = source.read()
	
	source.close()
	retval = Compiler().compile(code)
		
		#si la compilacion va Ok ...	
	#if retval!=0:
	#	sys.exit(retval)

	#si ha habido algun error
	#sys.exit(retval)		
	return retval

if __name__ == '__main__':
	try:
		print "Compilando fichero ",sys.argv[1]
		retval = run_compiler()
		finishParser()
		if retval==0:
			print "Generando codigo final ..."
			fcg = FCG(blockTable)
			fcg.main()
			print "Codigo final generado: final.ens"
			#debug
			#blockTable.printAll()
			#findebug
	except LexError,e:
		print "El token leido no se corresponde con un token del lenguaje"
		print "ERROR: ",e

	except FinalCodeException,e:
		print "ERROR: ",e

